package com.youdianda.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youdianda.constant.MessageConstant;
import com.youdianda.dto.SysUserDTO;
import com.youdianda.dto.SysUserPageDTO;
import com.youdianda.entity.SysRole;
import com.youdianda.entity.SysRoleMenu;
import com.youdianda.entity.SysUser;
import com.youdianda.result.PageResult;
import com.youdianda.result.Result;
import com.youdianda.service.SysRoleService;
import com.youdianda.service.SysUserService;
import com.youdianda.mapper.SysUserMapper;
import com.youdianda.vo.SysRoleVO;
import com.youdianda.vo.SysUserVO;
import org.apache.commons.collections4.ListUtils;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.xml.transform.Source;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author xliu
* @description 针对表【sys_user(用户表)】的数据库操作Service实现
* @createDate 2023-05-14 16:01:07
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService{

    @Autowired
    private SysRoleService sysRoleService;
    /**
     * 分页条件查询系统用户列表
     * @param sysUserPageDTO
     * @return
     */
    @Override
    public Result listSysUserPage(SysUserPageDTO sysUserPageDTO) {
        if (sysUserPageDTO.getPage() == null) {
            sysUserPageDTO.setPage("1");
        }
        if (sysUserPageDTO.getLimit() == null) {
            sysUserPageDTO.setLimit("10");
        }
        long current = Long.parseLong(sysUserPageDTO.getPage());
        long size = Long.parseLong(sysUserPageDTO.getLimit());
        // 分页条件模糊查询
        IPage<SysUser> page = new Page<>(current, size);
        page(page, Wrappers.<SysUser>lambdaQuery()
                .like(StringUtils.hasLength(sysUserPageDTO.getLogin_name()),
                        SysUser::getLogin_name, sysUserPageDTO.getLogin_name())
                .like(StringUtils.hasLength(sysUserPageDTO.getPhone()),
                        SysUser::getPhone, sysUserPageDTO.getPhone())
                .eq(StringUtils.hasLength(sysUserPageDTO.getStatus()),
                        SysUser::getStatus, sysUserPageDTO.getStatus())
                .orderByDesc(SysUser::getUpdate_date)
        );
        // 得到查询结果
        List<SysUser> sysUsers = page.getRecords();
        List<SysUserVO> sysUserVOS = new ArrayList<>();
        // 遍历
        for (SysUser sysUser : sysUsers) {
            // 创建系统用户vo
            SysUserVO sysUserVO = new SysUserVO();
            // 将系统用户对象数据复制到vo中
            BeanUtils.copyProperties(sysUser, sysUserVO);
            String roleIds = sysUser.getRole_id();
            // 解析用户的角色id
            List<String> roleIdlist = JSONObject.<List<String>>parseObject(roleIds, List.class);
            List<String> rolename = new ArrayList<>();
            if (roleIdlist != null) {
                // 遍历角色id，查询角色名字
                for (String roleId : roleIdlist) {
                    SysRole sysRole = sysRoleService.getById(roleId);
                    rolename.add(sysRole.getName());
                }
            }
            // 给角色vo的角色菜单列表和角色id赋值
            sysUserVO.setRole_id(roleIdlist);
            sysUserVO.setRolename(rolename);
            sysUserVOS.add(sysUserVO);
        }
        // 封装数据，返回
        PageResult pageResult = new PageResult((int) page.getTotal(), (int)  page.getPages(), (int)  page.getCurrent(),
                (int)  page.getSize(), sysUserVOS);
        return Result.success(pageResult);
    }

    /**
     * 根据id删除系统用户
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result deleteRoleById(String id) {
        if (id == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        // 删除
        removeById(id);
        return Result.success();
    }

    /**
     * 系统用户添加
     * @param sysUserDTO
     * @return
     */
    @Override
    @Transactional
    public Result addSysUser(SysUserDTO sysUserDTO) {
        if (!StringUtils.hasLength(sysUserDTO.getLogin_name())) {
            return Result.error(MessageConstant.LOGIN_NAME_NOT_FOUND);
        }
        // 根据登录名查询系统用户
        SysUser sysUser = getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getLogin_name, sysUserDTO.getLogin_name()));
        // 判断登录名是否重复
        if (sysUser != null) {
            return Result.error(MessageConstant.LOGIN_NAME_ALREADY_EXIST);
        }
        // 设置系统用户数据
        sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserDTO, sysUser);
        sysUser.setCreate_date(LocalDateTime.now());
        sysUser.setUpdate_date(LocalDateTime.now());
        sysUser.setRole_id(JSON.toJSONString(sysUserDTO.getRole_id()));
        sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUserDTO.getPassword().getBytes()));
        // 添加系统用户数据
        save(sysUser);
        return Result.success();
    }

    /**
     * 根据id查询系统用户详情
     * @param id
     * @return
     */
    @Override
    public Result getSysUserById(String id) {
        // 非空校验
        if (!StringUtils.hasLength(id)) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        // 根据id查询系统用户信息
        SysUser sysUser = getById(id);
        if (sysUser == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        SysUserVO sysUserVO = new SysUserVO();
        // 将系统用户对象数据复制到vo中
        BeanUtils.copyProperties(sysUser, sysUserVO);
        String roleIds = sysUser.getRole_id();
        // 解析用户的角色id
        List<String> roleIdlist = JSONObject.<List<String>>parseObject(roleIds, List.class);
        // 给角色vo的角色id赋值
        sysUserVO.setRole_id(roleIdlist);

        return Result.success(sysUserVO);
    }

    /**
     * 系统用户修改
     * @param sysUserDTO
     * @return
     */
    @Override
    public Result updateSysUser(SysUserDTO sysUserDTO) {
        String id = sysUserDTO.getId();
        String password = sysUserDTO.getPassword();
        String loginName = sysUserDTO.getLogin_name();
        // 非空校验
        if (!StringUtils.hasLength(id)) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        if (!StringUtils.hasLength(loginName)) {
            return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        if (!StringUtils.hasLength(password)) {
            return Result.error(MessageConstant.PASSWORD_EDIT_FAILED);
        }
        // 根据登录名查询除该id之外的系统用户
        SysUser sysUser = getOne(Wrappers.<SysUser>lambdaQuery()
                .eq(SysUser::getLogin_name, loginName)
                .ne(SysUser::getId, id)
        );
        // 判断登录名是否重复
        if (sysUser != null) {
            return Result.error(MessageConstant.LOGIN_NAME_ALREADY_EXIST);
        }
        // 修改系统用户数据
        update(Wrappers.<SysUser>lambdaUpdate()
                .set(StringUtils.hasLength(sysUserDTO.getName()), SysUser::getName, sysUserDTO.getName())
                .set(StringUtils.hasLength(password), SysUser::getPassword, DigestUtils.md5DigestAsHex(password.getBytes()))
                .set(StringUtils.hasLength(loginName), SysUser::getLogin_name, loginName)
                .set(StringUtils.hasLength(sysUserDTO.getEmail()), SysUser::getEmail, sysUserDTO.getEmail())
                .set(StringUtils.hasLength(sysUserDTO.getPhone()), SysUser::getPhone, sysUserDTO.getPhone())
                .set(sysUserDTO.getStatus() != null, SysUser::getStatus, sysUserDTO.getStatus())
                .set(sysUserDTO.getRole_id() != null, SysUser::getRole_id, JSON.toJSONString(sysUserDTO.getRole_id()))
                .eq(SysUser::getId, id)
        );
        return Result.success();
    }
}




